package com.cr.attach.exception;

import com.cr.common.exception.ServiceException;
import com.cr.common.response.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

/**
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 业务异常处理
     *
     * @param e 业务异常对象
     * @return {@link JsonResult}
     */
    @ExceptionHandler({ServiceException.class})
    public JsonResult handleServiceException(ServiceException e) {
        String msg = e.getMessage();
        log.error("发生业务异常: {}", msg);
        if (e.getCode() != null) {
            return JsonResult.error(e.getCode(), msg);
        }
        return JsonResult.error(msg);
    }

    /**
     * 上传异常处理
     *
     * @param e 上传异常对象
     * @return {@link JsonResult}
     */
    @ExceptionHandler({MaxUploadSizeExceededException.class})
    public JsonResult handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
        String msg = "超过了最大上载大小";
        log.error("发生上传异常: {}", e.getMessage());
        return JsonResult.error(msg);
    }

    /**
     * 系统异常处理
     *
     * @param e 系统异常对象
     * @return {@link JsonResult}
     */
    @ExceptionHandler({Throwable.class})
    public JsonResult handleThrowable(Throwable e) {
        log.error("发生系统异常", e);
        return JsonResult.error("服务器忙，请稍后再重试");
    }

}
